package com.example.myprojectoffeixue;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.localization.Gateway;
import com.localization.GatewayRequestUtil;
import com.localization.SendUtil;

import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
public class MyKgActivity extends Activity {
    ArrayList<SheBeiClass> l = new ArrayList<SheBeiClass>();
    private MyApplication m;
    private Listviewadapter ld;
    private String cmd;
    String name;
    public TextView tv;
    public boolean flag;
    public int flag2;
    private Dialog dialog1;
    // 接到消息，知道数据改变，刷新界面
    Handler hand = new Handler() {

        public void handleMessage(android.os.Message msg) {

            if (msg.what == 0) {
                Log.d("刷新","刷新");
                if (cmd.equals(msg.obj)) {
                    if (dialog1.isShowing()) {
                        dialog1.dismiss();
                    }
                    ld.notifyDataSetChanged();
                } else {
                    ld.notifyDataSetChanged();
                }

            } else if (msg.what == 3&&"1006".equals(cmd)) {
                String power = (String) msg.obj;
                Toast.makeText(MyKgActivity.this, power, Toast.LENGTH_SHORT).show();
            } else if (msg.what == 55) {
                if (dialog1.isShowing()) {
                    dialog1.dismiss();
                    Toast.makeText(MyKgActivity.this, "请求超时", Toast.LENGTH_SHORT).show();
                }
            } else if (msg.what == 60) {
                if (cmd.equals("1010")) {
                    HttpConnection.toastLog("检查到有人移动", MyKgActivity.this);
                }
            }else if(msg.what==10){
                ld.notifyDataSetChanged();
            }
        };
    };
    private ListView lv;

    // ----------------------界面的入口-------------------------

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_kg);
        runner.start();
        info();
    }

    @Override
    protected void onDestroy() {
        flag = false;
        super.onDestroy();
    }

    // 获取控件，添加条目的点击事件
    private void info() {
        cmd = "";
        flag = true;
        Intent it = getIntent();
        flag2 = it.getIntExtra("flag", -1);
        LinearLayout iv = (LinearLayout) findViewById(R.id.iv_mykaiguan);
        iv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();

            }
        });
        m = (MyApplication) getApplication();

        select_flag();

        dialog1 = new Dialog(this, R.style.myDialogTheme);
        dialog1.setContentView(R.layout.progressdialog);
        m.hand = hand;
        //wsc=m.c;
        lv = (ListView) findViewById(R.id.lv_mykg);
        if(l.size()!=0){
        ld = new Listviewadapter(l, this, cmd, dialog1);
        lv.setAdapter(ld);}
        if (flag2 == 7) {
            lv.setOnItemClickListener(new OnItemClickListener() {
                                          @Override
                                          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                              Intent it = new Intent(MyKgActivity.this, KongTiaoActivity.class);
                                              startActivity(it);
                                          }
                                      }


            );
        }


        if (flag2 == 6) {
            lv.setOnItemClickListener(new OnItemClickListener() {
                                          @Override
                                          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                              if (m.lsb6.size() != 0) {
                                                  m.ieee_ykq = m.lsb6.get(position).ieee;
                                                  m.port_ykq = m.lsb6.get(position).port;
                                                  m.mac_ykq = m.lsb6.get(position).mac;
                                              }
                                              Intent it = new Intent(MyKgActivity.this, MyYaoKongActivity.class);
                                              startActivity(it);
                                          }
                                      }


            );


        }


        //长按改名字
        if ("1006".equals(cmd)) {
            lv.setOnItemLongClickListener(new OnItemLongClickListener() {
                Dialog dialog;

                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                    tv = (TextView) view.findViewById(R.id.tv_listview);
                    dialog = new Dialog(MyKgActivity.this);
                    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    dialog.setContentView(R.layout.qudiankaiguandialog);
                    dialog.show();

                    TextView rename = (TextView) dialog.findViewById(R.id.rename);
                    TextView getdianliang = (TextView) dialog.findViewById(R.id.getdianliang);
                    rename.setOnClickListener(new View.OnClickListener() {
                        private EditText et;

                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                            final String cmd = "1002";
                            final String ieee = l.get(position).ieee;
                            final String port = l.get(position).port;
                            final String h = l.get(position).deviceId;
                            final String mac = l.get(position).mac;
                            Builder builder = new AlertDialog.Builder(MyKgActivity.this);
                            builder.setTitle("请输入");
                            builder.setIcon(android.R.drawable.ic_dialog_info);
                            et = new EditText(MyKgActivity.this);
                            et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});
                            builder.setView(et);
                            builder.setNegativeButton("取消", null);
                            builder.setPositiveButton("确定", new OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    name = et.getText().toString();
                                    Kuaiguanutil k = new Kuaiguanutil();
                                    k.ieee = l.get(position).ieee;
                                    k.port = l.get(position).port;
                                    k.deviceId = l.get(position).deviceId;
                                    k.deviceName = name;
                                    k.mac = l.get(position).mac;
                                    String l2 = JSON.toJSONString(k);
                                    l2 = AESUtil.encrypt(l2);
                                    HttpUtils httpUtils = new HttpUtils();
                                    RequestParams params = new RequestParams();
                                    params.setHeader("Content-Type", "application/json");
                                    try {
                                        params.setBodyEntity(new StringEntity(l2, "utf-8"));
                                    } catch (UnsupportedEncodingException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }

                                    httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.renameDevice, params,
                                            new RequestCallBack<String>() {

                                                @Override
                                                public void onFailure(HttpException arg0, String arg1) {
                                                    HttpConnection.toastLog("网络异常", MyKgActivity.this);
                                                }

                                                @Override
                                                public void onSuccess(ResponseInfo<String> arg0) {
                                                    if (arg0.result != null && !("".equals(arg0.result))) {
                                                        arg0.result = AESUtil.decrypt(arg0.result);
                                                        GateWay Gw2 = JSON.parseObject(arg0.result, GateWay.class);
                                                        if (0 == Gw2.status) {
                                                            l.get(position).deviceName = name;
                                                            ld.notifyDataSetChanged();
                                                        } else {
                                                            HttpConnection.toastLog("修改失败", MyKgActivity.this);
                                                        }

                                                    } else {
                                                        HttpConnection.toastLog("服务器错误", MyKgActivity.this);

                                                    }
                                                }

                                            });


                                }
                            });

                            builder.setNegativeButton("取消", null);
                            AlertDialog dialog1 = builder.create();
                            dialog1.show();

                        }
                    });

                    getdianliang.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String ieee = l.get(position).ieee;
                            String port = l.get(position).port;
                            final String mac = l.get(position).mac;
                            String s = "06";
                            Kuaiguanutil k = new Kuaiguanutil();
                            k.cmd = cmd;
                            k.ieee = ieee;
                            k.port = port;
                            k.status = s;
                            k.mac = mac;
                            String j = JSON.toJSONString(k);
                            if (!(Gateway.MacSocke.containsKey(k.mac))) {
                                if (m.flag3) {
                                    m.c.send(j);
                                }
                            } else {
                                String cmd = GatewayRequestUtil.createPowerSearchStr(ieee, port, mac);
                                Log.d("我发的命令", cmd);
                                SendUtil.Mac = mac;
                                SendUtil.cmd = cmd;
                                SendUtil.hand.sendEmptyMessage(0);
                            }
                            dialog.dismiss();
                        }
                    });

                    ImageView iv = (ImageView) dialog.findViewById(R.id.iv1_mydialog);
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });


                    return true;

                }


            });


        } else {

            lv.setOnItemLongClickListener(new OnItemLongClickListener() {

                private EditText et;

                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                    final String cmd = "1002";
                    final String ieee = l.get(position).ieee;
                    final String port = l.get(position).port;
                    final String h = l.get(position).deviceId;
                    final String mac = l.get(position).mac;
                    tv = (TextView) view.findViewById(R.id.tv_listview);
                    Builder builder = new AlertDialog.Builder(MyKgActivity.this);
                    builder.setTitle("重命名");
                    builder.setIcon(android.R.drawable.ic_dialog_info);
                    et = new EditText(MyKgActivity.this);
                    et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});
                    et.setHint("请输入新的设备名字");
                    builder.setView(et);
                    builder.setPositiveButton("确定", new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            name = et.getText().toString();
                            Kuaiguanutil k = new Kuaiguanutil();
                            k.cmd = cmd;
                            k.ieee = ieee;
                            k.port = port;
                            k.deviceId = h;
                            k.deviceName = name;
                            k.mac = mac;
                            String l2 = JSON.toJSONString(k);
                            l2 = AESUtil.encrypt(l2);
                            HttpUtils httpUtils = new HttpUtils();
                            RequestParams params = new RequestParams();
                            params.setHeader("Content-Type", "application/json");
                            try {
                                params.setBodyEntity(new StringEntity(l2, "utf-8"));
                            } catch (UnsupportedEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                            httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.renameDevice, params,
                                    new RequestCallBack<String>() {

                                        @Override
                                        public void onFailure(HttpException arg0, String arg1) {
                                            HttpConnection.toastLog("网络异常", MyKgActivity.this);
                                        }

                                        @Override
                                        public void onSuccess(ResponseInfo<String> arg0) {
                                            if (arg0.result != null && !("".equals(arg0.result))) {
                                                arg0.result = AESUtil.decrypt(arg0.result);
                                                GateWay Gw2 = JSON.parseObject(arg0.result, GateWay.class);
                                                if (0 == Gw2.status) {
                                                    l.get(position).deviceName = name;
                                                    ld.notifyDataSetChanged();
                                                } else {
                                                    HttpConnection.toastLog("修改失败", MyKgActivity.this);
                                                }

                                            } else {
                                                HttpConnection.toastLog("服务器错误", MyKgActivity.this);

                                            }
                                        }

                                    });


                        }
                    });
                    builder.setNegativeButton("取消", null);
                    AlertDialog dialog = builder.create();
                    dialog.show();


                    return true;
                }

            });
        }

    }



    Thread runner=new Thread() {

        @Override
        public void run() {
            if ("1006".equals(cmd) || "1007".equals(cmd)) {
                for (int i = 0; i < l.size(); i++) {
                    String ieee = l.get(i).ieee;
                    String port = l.get(i).port;
                    final String mac = l.get(i).mac;
                    String s = "02";
                    Kuaiguanutil k = new Kuaiguanutil();
                    k.cmd = cmd;
                    k.ieee = ieee;
                    k.port = port;
                    k.status = s;
                    k.mac = mac;
                    String j = JSON.toJSONString(k);
                    Log.d("cmdffffff", j);
                    if (!(Gateway.MacSocke.containsKey(k.mac))) {
                        if (m.flag3) {
                            m.c.send(j);
                        }
                    } else {
                        String cmd = GatewayRequestUtil.createDeviceStatusStr(ieee,port, mac);
                        Log.d("我发的命令", cmd);
                        SendUtil.Mac = mac;
                        SendUtil.cmd = cmd;
                        SendUtil.hand.sendEmptyMessage(0);
                        try {
                            sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

                super.run();
            }
        }};







    public void getdivce() {
        String UserName =m.userId;
        if (UserName != null) {
            GateWay Gw = new GateWay();
            Gw.userId = UserName;
            Gw.status = 1;
            String j = JSON.toJSONString(Gw);
            j = AESUtil.encrypt(j);
            HttpUtils httpUtils = new HttpUtils();
            RequestParams params = new RequestParams();
            params.setHeader("Content-Type", "application/json");
            try {
                params.setBodyEntity(new StringEntity(j, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            httpUtils.send(HttpRequest.HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/device/getDeviceList", params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            HttpConnection.toastLog("网络异常", MyKgActivity.this);

                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> arg0) {
                            if (arg0.result != null && !("".equals(arg0.result))) {
                                arg0.result = AESUtil.decrypt(arg0.result);
                                JSONObject jb = JSONObject.parseObject(arg0.result);
                                String status=jb.getString("status");
                                if("0".equals(status)){
                                    JSONArray ja = jb.getJSONArray("deviceList");
                                    m.m_gateway = (ArrayList<GateWay>) JSON.parseArray(ja.toString(), GateWay.class);
                                    m.Get();
                                    ld.notifyDataSetChanged();
                                }else{
                                    HttpConnection.toastLog("服务器错误", MyKgActivity.this);
                                }

                            } else {
                                HttpConnection.toastLog("服务器错误", MyKgActivity.this);

                            }
                        }

                    });

        }
    }




public void select_flag(){
    switch (flag2) {
        case 0:
            l.clear();
            l = m.lsb;
            cmd = "1007";
            break;
        case 1:
            l.clear();
            l = m.lsb1;
            cmd = "1005";
            break;

        case 2:
            l.clear();
            l = m.lsb2;
            cmd = "1010";
            break;

        case 3:
            l.clear();
            l = m.lsb3;
            cmd = "1008";
            break;


        case 4:
            l.clear();
            l = m.lsb4;
            break;

        case 5:
            l.clear();
            l = m.lsb5;
            cmd = "1006";
            break;


        case 6:
            l.clear();
            l = m.lsb6;
            cmd = "YKQ";
            break;


        case 8:
            l.clear();
            l = m.lsb8;
            cmd = "1007";
            break;

    }
}




















}   

	
	

